import React, { useCallback, useEffect, useState } from 'react';
import { Button, Input, Space, Table, Modal, message } from 'antd';
import type { GetProps } from 'antd';
import http from '../api/http';
import Column from 'antd/lib/table/Column';
import type { PaginationProps, TableProps } from 'antd';
import { DeleteOutlined, ExclamationCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Edit } from './edit';
type SearchProps = GetProps<typeof Input.Search>;
import { Divider, Flex, Tag } from 'antd';
import { Add } from "./add";
const { Search } = Input;
const { confirm } = Modal;
import type { IDisease } from '../types/disease'; // 假设存在IDisease类型

export default function Disease() {
    const [name, setName] = useState('');
    const [data, setData] = useState<IDisease[]>([]);
    const [pagination, setPagination] = useState({
        page: 1,
        size: 3,
        total: 0
    });
    // 用于记录选中的行ID
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

    const search = useCallback(() => {
        // 接口地址替换为疾病表的分页接口
        http.getList<IDisease>("disease/page", {
            page: pagination.page,
            size: pagination.size,
            name: name // 按疾病名称搜索
        }).then(res => {
            setData(res.data || []);
            setPagination(n => ({
                ...n,
                page: res.page || n.page,
                total: res.count || 0  
            }));
        }).catch(err => {
            console.error('获取疾病数据失败:', err);
        });
    }, [pagination.page, pagination.size, name]);

    useEffect(() => {
        search();
    }, [name, search]);

    const onSearch: SearchProps['onSearch'] = (value) => {
        setName(value);
        setPagination(prev => ({ ...prev, page: 1 }));
    };

    const selectOnChange: PaginationProps['onChange'] = (page, size) => {
        setPagination({ page: page, size: size, total: pagination.total });
    };

    // 处理单行删除
    const handleDelete = (id: number) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这条疾病记录吗？此操作不可撤销。',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                // 接口地址替换为疾病表的删除接口
                http.delete("disease", { id: id })
                    .then(() => {
                        message.success('删除成功');
                        search();
                        setSelectedRowKeys([]);
                    })
                    .catch(err => {
                        console.error('删除失败:', err);
                        message.error('删除失败');
                    });
            }
        });
    };

    // 处理批量删除
    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的记录');
            return;
        }

        confirm({
            title: '批量删除',
            icon: <ExclamationCircleOutlined />,
            content: `确定要删除选中的 ${selectedRowKeys.length} 条疾病记录吗？此操作不可撤销。`,
            okText: '确认',
            cancelText: '取消',
            onOk() {
                // 接口地址替换为疾病表的批量删除接口
                http.deleteBatch('disease/dels', selectedRowKeys)
                    .then(() => {
                        message.success('批量删除成功');
                        search();
                        setSelectedRowKeys([]);
                    })
                    .catch(err => {
                        console.error('批量删除失败:', err);
                        message.error('批量删除失败');
                    });
            }
        });
    };

    // 行选择配置
    const rowSelection: TableProps<IDisease>['rowSelection'] = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
    };

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [currentEditData, setCurrentEditData] = useState<IDisease | undefined>();

    const showModal = () => {
        setIsModalOpen(true);
    };

    const editShowModal = (record: IDisease) => {
        setCurrentEditData(record);
        setEditModalOpen(true);
    };

    const editHandleCancel = () => {
        setEditModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    return (
        <>
            <Space style={{ marginBottom: 16 }}>
                <Search
                    placeholder="请输入疾病名称"
                    onSearch={onSearch}
                    style={{ width: 200 }}
                    allowClear
                />
                <Button type="primary" onClick={showModal}>添加</Button>
                <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={handleBatchDelete}
                    disabled={selectedRowKeys.length === 0}
                >
                    批量删除
                </Button>
            </Space>

            <Table<IDisease>
                dataSource={data}
                rowKey="id"
                pagination={{
                    current: pagination.page,
                    pageSize: pagination.size,
                    total: pagination.total,
                    showQuickJumper: true,
                    showTotal: (total) => '共有' + total + '条数据',
                    pageSizeOptions: ['3', '5', '8'],
                    showSizeChanger: true,
                    onChange: selectOnChange,
                    align: 'center'
                }}
                rowSelection={rowSelection}
            >
                <Column title="编号" dataIndex="id" key="id" />
                <Column title="疾病编码" dataIndex="code" key="code" />
                <Column title="疾病名称" dataIndex="name" key="name" />
                <Column title="就诊科室" dataIndex="deptname" key="deptname" />
                <Column 
                    title="预警等级" 
                    dataIndex="warnlevel" 
                    key="warnlevel" 
                    render={(level) => {
                        switch(level) {
                            case '一级': return <Tag color="red">{level}</Tag>;
                            case '二级': return <Tag color="orange">{level}</Tag>;
                            case '三级': return <Tag color="blue">{level}</Tag>;
                            default: return level;
                        }
                    }} 
                />
                <Column title="就医期限" dataIndex="treatperiod" key="treatperiod" />
                <Column title="异常类型" dataIndex="exceptiontype" key="exceptiontype" />
                <Column 
                    title="是否职业病" 
                    dataIndex="isoccupational" 
                    key="isoccupational" 
                    render={(val) => val === 1 ? 
                        <Tag icon={<CheckCircleOutlined />} color="success">是</Tag> : 
                        <Tag icon={<CloseCircleOutlined />} color="error">否</Tag>
                    } 
                />
                <Column 
                    title="适用性别" 
                    dataIndex="gender" 
                    key="gender" 
                    render={(val) => val === 0 ? '男' : '女'} 
                />
                <Column title="疾病别名" dataIndex="othername" key="othername" />
                <Column title="医学解释" dataIndex="medicalinterpret" key="medicalinterpret" width={200} />
                <Column title="常见原因" dataIndex="reason" key="reason" width={200} />
                <Column title="就医建议" dataIndex="advice" key="advice" width={200} />
                <Column title="创建时间" dataIndex="createtime" key="createtime" />
                <Column title="更新时间" dataIndex="updatetime" key="updatetime" />
                <Column
                    title="操作"
                    key="action"
                    render={(_, record: IDisease) => (
                        <Space size="middle">
                            <Button
                                type="primary"
                                size="small"
                                onClick={() => editShowModal(record)}
                            >
                                编辑
                            </Button>
                            <Button
                                danger
                                size="small"
                                onClick={() => handleDelete(record.id)}
                            >
                                删除
                            </Button>
                        </Space>
                    )}
                />
            </Table>
            <Add onSuccess={search} isModalOpen={isModalOpen} handleCancel={handleCancel}></Add>
            <Edit onSuccess={search} EditModalOpen={editModalOpen} EditHandleCancel={editHandleCancel} editData={currentEditData}></Edit>
        </>
    );
}